package controller

import (
	"admin/contrib/session"
	"admin/model"
	"common/helper"
	"encoding/json"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
)

type WhiteListController struct{}

type whiteListForm_t struct {
	IP     string `json:"ip"`
	Remark string `json:"remark"`
}

func (that *WhiteListController) Insert(ctx *fasthttp.RequestCtx) {

	param := whiteListForm_t{}
	body := ctx.PostBody()

	err := json.Unmarshal(body, &param)
	if err != nil {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	admin := session.AdminGet(ctx)

	err = model.WhiteListInsert(admin["id"], admin["name"], param.IP, param.Remark)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}

func (that *WhiteListController) List(ctx *fasthttp.RequestCtx) {

	page := ctx.QueryArgs().GetUintOrZero("page")
	pageSize := ctx.QueryArgs().GetUintOrZero("page_size")
	startTime := string(ctx.QueryArgs().Peek("start_time"))
	endTime := string(ctx.QueryArgs().Peek("end_time"))
	createdName := string(ctx.QueryArgs().Peek("created_name"))
	ip := string(ctx.QueryArgs().Peek("ip"))

	if page < 1 {
		page = 1
	}

	if pageSize < 10 || pageSize > 500 {
		helper.RetData(ctx, false, "参数错误")
		return
	}

	ex := g.Ex{}
	if ip != "" {
		ex["ip"] = ip
	}
	if createdName != "" {
		ex["created_name"] = createdName
	}
	data, err := model.WhiteListList(startTime, endTime, ex, page, pageSize)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, data)
}

func (that *WhiteListController) Delete(ctx *fasthttp.RequestCtx) {

	id := string(ctx.QueryArgs().Peek("id"))
	if !helper.CtypeDigit(id) {
		helper.RetData(ctx, false, "参数错误")
	}

	admin := session.AdminGet(ctx)

	err := model.WhiteListDelete(admin["name"], id)
	if err != nil {
		helper.RetData(ctx, false, err.Error())
		return
	}

	helper.RetData(ctx, true, "成功")
}
